package cn.tomoya.module.index.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.tomoya.common.BaseController;
import cn.tomoya.common.config.SiteConfig;
import cn.tomoya.exception.Result;
import cn.tomoya.module.reply.service.ReplyService;
import cn.tomoya.module.security.JwtTokenUtil;
import cn.tomoya.module.security.JwtUser;
import cn.tomoya.module.security.core.MyUserDetailService;
import cn.tomoya.module.security.entity.Role;
import cn.tomoya.module.security.service.RoleService;
import cn.tomoya.module.topic.entity.Topic;
import cn.tomoya.module.topic.service.TopicService;
import cn.tomoya.module.user.entity.User;
import cn.tomoya.module.user.service.UserService;
import cn.tomoya.util.FileUploadEnum;
import cn.tomoya.util.FileUtil;
import cn.tomoya.util.identicon.Identicon;

/**
 * Created by tomoya.
 * Copyright (c) 2016, All Rights Reserved.
 * http://tomoya.cn
 */
@Controller
public class IndexController extends BaseController {

    @Autowired
    private TopicService topicService;
    @Autowired
    private ReplyService replyService;
    @Autowired
    private UserService userService;
    @Autowired
    private SiteConfig siteConfig;
    @Autowired
    private Identicon identicon;
    @Autowired
    private FileUtil fileUtil;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
     private MyUserDetailService myUserDetailService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private RoleService roleService;
    /**
     * 首页
     *
     * @return
     */
    @GetMapping("/")
    public String index(String tab, Integer p, Model model) {
        String sectionName = tab;
        if (StringUtils.isEmpty(tab)) tab = "1";
        String escapeHtml = StringEscapeUtils.escapeHtml(tab);
        String param = StringEscapeUtils.escapeJavaScript(escapeHtml);
        if(!StringUtils.isEmpty(tab)){
            if(!"1".equals(tab) && !"2".equals(tab)){
                param="1";
            }
        }

        Page<Topic> page = topicService.page(p == null ? 1 : p, siteConfig.getPageSize(), param);
        String baseUrl = siteConfig.getBaseUrl();
        List<String> tabList = new ArrayList<String>();
        tabList.add("2");
        tabList.add("3");
        tabList.add("4");
        List<Topic> publishTopicList = topicService.findByTabIn(tabList);
        model.addAttribute("page", page);
        model.addAttribute("publishTopicList", publishTopicList);
        model.addAttribute("tab", param);
        model.addAttribute("baseUrl",baseUrl);
        model.addAttribute("sectionName", sectionName);
        model.addAttribute("user", getUser());
        return render("/index");
    }

    /**
     * 进入登录页
     *
     * @return
     */
    @RequestMapping("/login")
    public String toLogin(String imagecodeText, Model model, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        if (getUser() != null) {
            return redirect(response, "/");
        }
        //model.addAttribute("s", s);
        return render("/login");
    }




   /*@GetMapping("/login/getCode")
    public String getCode(HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> map = new HashMap<>();
        String piccode =(String) request.getSession().getAttribute("piccode");
       HttpSession session=request.getSession();
       ServletContext context=session.getServletContext();
       String piccode1 = (String) context.getAttribute("piccode");
       String s = (String)request.getSession().getAttribute("piccode");
        System.out.println(piccode+"ppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp");
        System.out.println(s);
        map.put("piccode",piccode);
        map.put("s",s);
        return  render("/login");
    }*/

    /*@GetMapping("/login/getCode")
    public Map<String,Object> getCode(HttpServletRequest request,HttpServletResponse response){
        Map<String,Object> map = new HashMap<>();
        String piccode =(String) request.getSession().getAttribute("piccode");
        String s = (String)request.getSession().getAttribute("piccode");
        System.out.println(piccode+"ppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp");
        System.out.println(s);
        map.put("piccode",piccode);
        map.put("s",s);
        return  map;
    }*/


    @GetMapping("/ssologin")
    public String createAuthenticationToken(String token,String tab, Integer p, Model model)
            throws AuthenticationException
    {

        JwtUser jwtUsr = jwtTokenUtil.getUserFromToken(token);
        String tokenUserName = jwtUsr.getUsername();
        if(tokenUserName== null || "".equals(tokenUserName)){
//            跳转登录
            return render("/login");
        }
        User user = userService.findByUsername(tokenUserName);
        if(user == null){
            user = new User();
            Date now = new Date();
            user.setUsername(tokenUserName);
            user.setPassword(new BCryptPasswordEncoder().encode("abc123"));
            user.setInTime(now);
            user.setOrgname(jwtUsr.getOrgName());
            user.setNickname(jwtUsr.getNickName());
            user.setBzyId(jwtUsr.getId());

            Role role = roleService.findById(3);
            Set<Role> roles = new HashSet<>();
            roles.add(role);
            user.setRoles(roles);

            String avatarName = UUID.randomUUID().toString();
            user.setAvatar(siteConfig.getBaseUrl() + "static/images/avatar/" + avatarName + ".png");
            userService.save(user);
        }
        user.setNickname(jwtUsr.getNickName());
        user.setOrgname(jwtUsr.getOrgName());
        userService.updateUser(user);
        // Perform the security
        final Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),"abc123"));
        SecurityContextHolder.getContext().setAuthentication(authentication);

        return this.index(tab,p,model);
    }

    /**
     * 进入注册页面
     *
     * @return
     */
    /*@GetMapping("/register")
    public String toRegister(HttpServletResponse response) {
        if (getUser() != null) {
            return redirect(response, "/");
        }
        return render("/register");
    }*/

    /**
     * 注册验证
     *
     * @param username
     * @param password
     * @return
     */
    /*@PostMapping("/register")
    public String register(String username, String password, HttpServletResponse response, Model model) {
        User user = userService.findByUsername(username);
        if (user != null) {
            model.addAttribute("errors", "用户名已经被注册");
        } else if (StringUtils.isEmpty(username)) {
            model.addAttribute("errors", "用户名不能为空");
        } else if (StringUtils.isEmpty(password)) {
            model.addAttribute("errors", "密码不能为空");
        } else {
            Date now = new Date();
            String avatarName = UUID.randomUUID().toString();
            identicon.generator(avatarName);
            user = new User();
            user.setUsername(username);
            user.setPassword(new BCryptPasswordEncoder().encode(password));
            user.setInTime(now);
            user.setAvatar(siteConfig.getBaseUrl() + "static/images/avatar/" + avatarName + ".png");
            userService.save(user);
            return redirect(response, "/login?s=reg");
        }
        return render("/register");
    }*/

    /**
     * 上传
     *
     * @param file
     * @return
     */
    @GetMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                String requestUrl = fileUtil.uploadFile(file, FileUploadEnum.FILE);
                return Result.success(requestUrl);
            } catch (IOException e) {
                e.printStackTrace();
                return Result.error("上传失败");
            }
        }
        return Result.error("文件不存在");
    }

}
